import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:yt_devops/components/app_permission/permission_widget.dart';
import 'package:yt_devops/components/brn/brn_bottom_button_panel.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/add_mains_electricity_price/views/effective_data_widget.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/add_mains_electricity_price/views/effective_date_widgets.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/add_mains_electricity_price/views/item_tow_checkbox_widget.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/add_mains_electricity_price/views/mains_hours_set_widgets.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/add_mains_electricity_price/views/peak_and_plateau_time_widget.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_elec_price_setting_model.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_mains_elec_detail/site_mains_elec_detail_controller.dart';
import 'package:yt_devops/pages/site/site_setting/site_setting_base_info/widgets/item_widget.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';

import '../../../../../components/app_bar/app_bar_widget.dart';
import '../elec_price_title_widget.dart';

class SietMainsElecDetailView extends GetView<SietMainsElecDetailController> {
  SietMainsElecDetailView({Key? key}) : super(key: key);

  @override
  final controller = Get.put(SietMainsElecDetailController());

  @override
  Widget build(BuildContext context) {

    return GetBuilder<SietMainsElecDetailController>(
      init: controller,
      builder: (controller) {
        return Scaffold(
          resizeToAvoidBottomInset: true,
          backgroundColor: Colour.backgroundColor,
          appBar: AppBarWidget.withRightActions(
            ResKey.marketElePriceDetails.tr,
            actions: [
          PermissionWidget(permissionStringList:
          const [PermissionConstant.homeSiteManageSettingElectricitySettingGridEdit],
            child: Visibility(
                visible: !controller.isEnableEdit,
                child: IconButton(
                  icon: Image.asset(ImageAssets.siteSettingBaseInfoEdit),
                  onPressed: controller.edit,
                ),
              ))
            ],
          ),
          body: controller.isEnableEdit
              ? Container(

                        child:
                        ListView(padding: EdgeInsets.zero, children: [
                          Container(
                            height: 10,
                            color: Colour.backgroundColor,
                          ),
              Container(
                clipBehavior: Clip.hardEdge,
                margin: const EdgeInsets.only(left: 16,right: 16),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.white,
                ),
                child:Column(
                    children: [ElecPriceTitleWidget(controller.titleStringList[0]),
                          ItemWidget(controller.titleDetailList[0],
                              controller.ruleNameController,
                              unitString: controller.unitList[0],
                              titleColor: Colour.otherTextColor,
                              inputTextColor: Colour.mainTextColor,
                              titleFont: 14,
                              isRequired: true,
                              isCanEdit: true, textChangeCallBack: (str) {
                                controller.checkCommitStatus();
                              }),
                          ItemTowCheckboxWidget(
                            ResKey.siteSettingElectricityEffectiveStatus.tr,
                            ResKey.siteSettingEffective.tr,
                            ResKey.siteSettingUnEffective.tr,
                            controller.status, (index) {
                            controller.status = index;
                          },isRequired: true,),
                          ])),
                          Container(
                            height: 10,
                            color: Colour.backgroundColor,
                          ),
              Container(
                clipBehavior: Clip.hardEdge,
                margin: const EdgeInsets.only(left: 16,right: 16),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.white,
                ),
                child:Column(
                    children: [ElecPriceTitleWidget(controller.titleStringList[1]),
                          ItemWidget(controller.titleDetailList[1],
                              controller.powerElementController,
                              unitString: controller.unitList[1],
                              titleColor: Colour.otherTextColor,
                              inputTextColor: Colour.mainTextColor,
                              titleFont: 14,
                              isCanEdit: true, textChangeCallBack: (str) {
                                controller.checkCommitStatus();
                              }),
                          ItemTowCheckboxWidget(
                            ResKey.siteSettingElectricityBaseBillType.tr,
                            ResKey.capacity.tr,
                            ResKey.demand.tr,
                            controller.electricityType,
                                (index) {
                              controller.electricityType = index;
                            },
                            isShowDivider: true,
                          ),
                          ItemWidget(controller.titleDetailList[2],
                              controller.maxCapacityController,
                              unitString: controller.unitList[2],
                              titleColor: Colour.otherTextColor,
                              inputTextColor: Colour.mainTextColor,
                              titleFont: 14,
                              isCanEdit: true, textChangeCallBack: (str) {
                                controller.checkCommitStatus();
                              }),
                          ItemWidget(controller.titleDetailList[3],
                              controller.needPriceController,
                              unitString: controller.unitList[3],
                              titleColor: Colour.otherTextColor,
                              inputTextColor: Colour.mainTextColor,
                              titleFont: 14,
                              isShowDivider: false,
                              isCanEdit: true, textChangeCallBack: (str) {
                                controller.checkCommitStatus();
                              })])),
                          Container(
                            height: 10,
                            color: Colour.backgroundColor,
                          ),
              Container(
                clipBehavior: Clip.hardEdge,
                margin: const EdgeInsets.only(left: 16,right: 16),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.white,
                ),
                child:Column(
                    children: [ElecPriceTitleWidget(controller.titleStringList[2]),
                          ItemWidget(
                            controller.titleDetailList[4],
                            controller.maxPriceController,
                            unitString: controller.unitList[4],
                            titleColor: Colour.otherTextColor,
                            inputTextColor: Colour.mainTextColor,
                            titleFont: 14,
                            isCanEdit: true,
                          ),
                          ItemWidget(
                            controller.titleDetailList[5],
                            controller.peakPriceController,
                            unitString: controller.unitList[5],
                            titleColor: Colour.otherTextColor,
                            inputTextColor: Colour.mainTextColor,
                            titleFont: 14,
                            isCanEdit: true,
                          ),
                          ItemWidget(
                            controller.titleDetailList[6],
                            controller.averageProtectController,
                            unitString: controller.unitList[6],
                            titleColor: Colour.otherTextColor,
                            inputTextColor: Colour.mainTextColor,
                            titleFont: 14,
                            isCanEdit: true,
                          ),
                          ItemWidget(
                            controller.titleDetailList[7],
                            controller.valleyReleaseController,
                            unitString: controller.unitList[7],
                            titleColor: Colour.otherTextColor,
                            inputTextColor: Colour.mainTextColor,
                            titleFont: 14,
                            isCanEdit: true,
                          )])),
                          Container(
                            height: 10,
                            color: Colour.backgroundColor,
                          ),
                          EffectiveDateWidgets(controller.timeDateList, () {
                            controller.updateTimeList();
                          }, (index) {
                            controller.deleteTimeList(index);
                          }, () {
                            controller.update();
                          },isRequired: true,),
                          Container(
                            height: 10,
                            color: Colour.backgroundColor,
                          ),
                          MainsHoursSetWidgets(controller.peakAndPlateauList, () {
                            controller.updatePeakAndPlateauListList();
                          }, (index) {
                            controller.deletePeakAndPlateauListList(index);
                          }, () {
                            controller.update();
                          }, () {
                            controller.update();
                          }),
                          Container(
                            height: 10,
                            color: Colour.backgroundColor,
                          ),
                        ]),
                )
              : ListView(
                  children: [
                    Container(
                      margin: EdgeInsets.only(bottom: 10, top: 10),
                      color: Colour.backgroundColor,
                      child: Column(
                        children: [
                          Container(
                            height: 160,
                        clipBehavior: Clip.hardEdge,
                        margin: const EdgeInsets.only(left: 16,right: 16),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          color: Colors.white,),
                            child: GetBuilder<SietMainsElecDetailController>(
                                builder: (controller) {
                              List<InfoModel> basicList = [
                                InfoModel(ResKey.basicInfo.tr, ''),
                                InfoModel(
                                    ResKey.siteSettingElectricityRoleName.tr,
                                    controller.model.name.toString()),
                                InfoModel(
                                    ResKey.siteSettingElectricityEffectiveStatus
                                        .tr,
                                    controller.model.status == 0
                                        ? ResKey.siteSettingUnEffective.tr
                                        : ResKey.siteSettingEffective.tr),
                              ];
                              return listWidget(count: 3, items: basicList!);
                            }),
                          ),
                          Container(

                            margin: const EdgeInsets.only(left: 16,right: 16,top: 10),
                            clipBehavior: Clip.hardEdge,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              color: Colors.white,
                            ),
                            height: 260,
                            // color: Colors.white,
                            child: GetBuilder<SietMainsElecDetailController>(
                                builder: (controller) {
                              List<InfoModel> basicList = [
                                InfoModel(ResKey.basicEleFee.tr, ''),
                                InfoModel(
                                    ResKey.siteSettingElectricityPowerFactor.tr,
                                    controller.model.powerFactor ?? ''),
                                InfoModel(
                                    ResKey
                                        .siteSettingElectricityBaseBillType.tr,
                                    controller.model.electricityType == 0
                                        ? ResKey.demandCharge.tr
                                        : ResKey.capacityCharge.tr), // 0需量电费  1容量电费
                                InfoModel(
                                    ResKey.siteSettingElectricityMaxNeed.tr,
                                    '${controller.model.maxDemand ?? ''}kW'),
                                InfoModel(
                                    ResKey
                                        .siteSettingElectricityNeedCapacityBill
                                        .tr,
                                    '${controller.model.demandElectrovalency ?? ''}${controller.monetaryUnitName}'),
                              ];
                              return listWidget(count: 5, items: basicList);
                            }),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 10,left: 16,right: 16),
                            clipBehavior: Clip.hardEdge,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              color: Colors.white,
                            ),
                            child: GetBuilder<SietMainsElecDetailController>(
                                builder: (controller) {
                              List<InfoModel> basicList = [];
                              if (controller.model.effectiveTimeList != null) {
                                for (int i = 0;
                                    i <
                                        controller
                                            .model.effectiveTimeList!.length;
                                    i++) {
                                  EffectiveTimeList time =
                                      controller.model.effectiveTimeList![i];
                                  basicList.add(InfoModel(
                                      '${ResKey.siteSettingDate.tr}${i + 1}',
                                      '${time.effectiveTime} - ${time.expirationTime}'));
                                }
                              }
                              basicList.insert(
                                  0,
                                  InfoModel(
                                      ResKey.siteSettingEffectiveDate.tr, ''));
                              return listWidget(
                                  count: basicList.length, items: basicList);
                            }),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 10,left: 16,right: 16),
                            clipBehavior: Clip.hardEdge,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(8),
                              color: Colors.white,
                            ),
                            child: GetBuilder<SietMainsElecDetailController>(
                                builder: (controller) {
                              List<PeriodTime> basicList = [];
                              if (controller.model.hoursPriceList != null) {
                                for (int i = 0;
                                    i < controller.model.hoursPriceList!.length;
                                    i++) {
                                  HoursPriceList time =
                                      controller.model.hoursPriceList![i];
                                  String priceType = '';
                                  if (time.type == 0) {
                                    priceType = ResKey.sharpElePrice.tr;
                                  } else if (time.type == 1) {
                                    priceType = ResKey.peakElePrice.tr;
                                  } else if (time.type == 2) {
                                    priceType = ResKey.averageElePrice.tr;
                                  } else if (time.type == 3) {
                                    priceType = ResKey.valleyElePrice.tr;
                                  }
                                  basicList.add(PeriodTime(
                                      '${ResKey.siteSettingElectricityTimeStage.tr}$i',
                                      '${time.intervalStartTime} - ${time.intervalEndTime}',
                                      ResKey.siteSettingElectricityPriceType.tr,
                                      priceType));
                                }
                              }
                              basicList.insert(
                                0,
                                PeriodTime(
                                    ResKey.peakValleyElePrices.tr, '', '', ''),
                              );
                              return periodTimeListWidget(
                                  count: basicList.length, items: basicList);
                            }),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
          bottomNavigationBar: controller.isEnableEdit?Container(
            color: Colour.white,
            padding: EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
            child: YtBrnBottomButtonPanel(
                enableMainButton: controller.isEnableCommit,
                mainButtonName: ResKey.save.tr,
                mainButtonOnTap: () => controller.save(),
                secondaryButtonName: ResKey.cancel.tr,
                enableSecondaryButton: true,
                secondaryButtonBorder:
                Border.all(color: Colour.dividerColor),
                secondaryButtonOnTap: () =>
                    controller.cancelEdit()),
          ):null,
        );
      },
    );
  }

  Widget periodTimeListWidget({int? count, List<PeriodTime>? items}) {
    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: count,
      itemBuilder: (BuildContext context, int index) {
        if (items != null && items.isNotEmpty) {
          if (index == 0) {
            return Column(
              children: [
                titleWidget(items[index].timeName),
                Divider(height: 1, color: Colour.dividerColor),
              ],
            );
          } else if (index == count! - 1) {
            return Column(
              children: [
                periodTimeWidget(
                    items[index].timeName,
                    items[index].timeContent,
                    items[index].elecTypeName,
                    items[index].elecTypeContent),
              ],
            );
          } else {
            return Column(
              children: [
                periodTimeWidget(
                    items[index].timeName,
                    items[index].timeContent,
                    items[index].elecTypeName,
                    items[index].elecTypeContent),
                const Divider(
                  color: Colour.dividerColor,
                  height: 1,
                  indent: 16,
                  endIndent: 0,
                ),
              ],
            );
          }
        }
        return Container(); // 返回一个空的Widget
      },
    );
  }

  Widget periodTimeWidget(String leftTimeName, String rightTimeContent,
      String leftElecTypeName, String rightElecTypeContent,
      {int textHeight = 80}) {
    return Container(
      height: textHeight.toDouble(),
      padding: EdgeInsets.only(left: 16.w, right: 16.w, top: 16, bottom: 16),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                leftTimeName,
                style: TextStyles.styleWith(
                  14.sp,
                  color: Colour.otherTextColor,
                ),
              ),
              Text(
                rightTimeContent,
                style: TextStyles.styleWith(
                  14.sp,
                  color: Colour.mainTextColor,
                ),
              ),
            ],
          ),
          SizedBox(
            height: 4,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                leftElecTypeName,
                style: TextStyles.styleWith(
                  14.sp,
                  color: Colour.otherTextColor,
                ),
              ),
              Text(
                rightElecTypeContent,
                style: TextStyles.styleWith(
                  14.sp,
                  color: Colour.mainTextColor,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget listWidget({int? count, List<InfoModel>? items}) {
    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: count,
      itemBuilder: (BuildContext context, int index) {
        if (items != null && items.isNotEmpty) {
          if (index == 0) {
            return Column(
              children: [
                titleWidget(items[index].name??''),
                Divider(height: 1, color: Colour.dividerColor),
              ],
            );
          } else if (index == count! - 1) {
            return Column(
              children: [
                infoWidget(items[index].name, items[index].content),
              ],
            );
          } else {
            return Column(
              children: [
                infoWidget(items[index].name, items[index].content),
                const Divider(
                  color: Colour.dividerColor,
                  height: 1,
                  indent: 16,
                  endIndent: 0,
                ),
              ],
            );
          }
        }
        return Container(); // 返回一个空的Widget
      },
    );
  }

  Widget infoWidget(String leftText, String rightText, {int textHeight = 50}) {
    return Container(
      height: textHeight.toDouble(),
      padding: EdgeInsets.only(left: 16.w, right: 16.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            leftText,
            style: TextStyles.styleWith(
              14.sp,
              color: Colour.otherTextColor,
            ),
          ),
          Text(
            rightText,
            style: TextStyles.styleWith(
              14.sp,
              color: Colour.mainTextColor,
            ),
          ),
        ],
      ),
    );
  }

  Widget titleWidget(String titleText) {
    return Container(
      height: 50,
      padding: EdgeInsets.only(
        left: 16.w,
      ),
      alignment: Alignment.centerLeft,
      child: Text(
        titleText,
        softWrap: true,
        style: TextStyles.styleWith(
          18.sp,
          color: Colour.mainTextColor,
        ).mediumStyle,
      ),
    );
  }

  

  _addEffectiveDataWidgets(BuildContext context) {
    List<Widget> list = [];
    if (controller.timeDateList.length > 1) {
      for (int i = 1; i < controller.timeDateList.length; i++) {
        var widget = EffectiveDataWidget(
          context,
          '${ResKey.siteSettingDate.tr}${i + 1}',
          controller.timeDateList[i]['effectiveTime'],
          controller.timeDateList[i]['expirationTime'],
          (startDateTime, endDateTime) {
            controller.timeDateList[i] = {
              'effectiveTime': startDateTime,
              'expirationTime': endDateTime,
            };
            controller.update();
          },
          () {
            controller.deleteTimeList(i);
          },
          isDelete: true,
        );
        list.add(widget);
      }
    }
    return SizedBox(
      height: (controller.timeDateList.length - 1) * 55,
      child: Column(
        children: list,
      ),
    );
  }

  _addPeakAndPlateauWidgets(BuildContext context) {
    List<Widget> list = [];
    if (controller.peakAndPlateauList.length > 1) {
      for (int i = 1; i < controller.peakAndPlateauList.length; i++) {
        var widget = PeakAndPlateauTimeWidget(
          context,
          '${ResKey.siteSettingElectricityTimeStage.tr}${i + 1}',
          controller.peakAndPlateauList[i]['type'].toString(),
          controller.peakAndPlateauList[i]['intervalStartTime'],
          controller.peakAndPlateauList[i]['intervalEndTime'],
          (startDateTime, endDateTime) {
            controller.peakAndPlateauList[i] = {
              'intervalStartTime': startDateTime,
              'intervalEndTime': endDateTime,
              'type': 0
            };
            controller.update();
          },
          () {
            controller.deletePeakAndPlateauListList(i);
          },
          (String index) {
            controller.peakAndPlateauList[i]['type'] = index.toString();
            controller.update();
          },
          isDelete: true,
        );
        list.add(widget);
      }
    }
    return SizedBox(
      height: (controller.peakAndPlateauList.length - 1) * 110,
      child: Column(
        children: list,
      ),
    );
  }
}

class InfoModel {
  String name;
  String content;

  InfoModel(this.name, this.content);
}

class PeriodTime {
  // 时间段
  String timeName;
  String timeContent;

  // 电价类型
  String elecTypeName;
  String elecTypeContent;

  PeriodTime(
      this.timeName, this.timeContent, this.elecTypeName, this.elecTypeContent);
}
